package com.hoshiicloud.user.controller.usercenter;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.user.controller.BaseController;
import com.hoshiicloud.user.dto.userCenter.MemberDto;
import com.hoshiicloud.user.entity.usercenter.MemberAccount;
import com.hoshiicloud.user.entity.usercenter.MemberIntegration;
import com.hoshiicloud.user.entity.usercenter.PlatConsumer;
import com.hoshiicloud.user.param.PlatStoreConsumerPageParam;
import com.hoshiicloud.user.param.usercenter.PlatConsumerPageParam;
import com.hoshiicloud.user.param.usercenter.PlatConsumerUpdateParam;
import com.hoshiicloud.user.service.usercenter.IMemberAccountService;
import com.hoshiicloud.user.service.usercenter.IMemberIntegrationService;
import com.hoshiicloud.user.service.usercenter.IPlatConsumerService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiSort;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 平台消费者信息Controller类
 *
 * @author : yangcheng
 * @date : 2019/5/9 14:45
 * @mail : maiboyc@163.com
 **/
@RestController
@RequestMapping("/usercenter/platConsumer")
@Api(value = "租户平台消费者", tags = {"租户平台消费者"}, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiSort(31)
public class PlatConsumerController extends BaseController {

    // 平台消费者信息Service
    @Autowired
    private IPlatConsumerService platMemberService;

    // 租户会员信息Service


    // 平台消费者账户Service
    @Autowired
    private IMemberAccountService memberAccountService;

    // 平台消费者积分Service
    @Autowired
    private IMemberIntegrationService memberIntegrationService;

    /**
     * 根据ID查询平台消费者信息
     * @param id 用户ID
     * @return Response
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询", notes = "根据ID查询平台消费者信息", consumes = MediaType.ALL_VALUE)
    public Response<PlatConsumer> getById(@PathVariable("id") Long id) {
        Response rs;
        try {
            rs = Response.data(platMemberService.getById(id));
        } catch (Exception e) {
            logger.error("根据ID查询平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID组查询平台消费者信息
     * @param ids 用户ID组
     * @return Response
     */
    @GetMapping("/getByIds")
    @ApiOperation(value = "根据ID组查询", notes = "根据ID组查询平台消费者信息", consumes = MediaType.ALL_VALUE)
    public Response getByIds(@RequestParam("ids") List<Long> ids) {
        Response rs;
        try {
            rs = Response.data(platMemberService.getByIds(ids));
        } catch (Exception e) {
            logger.error("根据ID组查询平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据邀请码查询平台消费者信息
     * @param inviteCode  用户名称
     * @return Response
     */
    @GetMapping("/find/{inviteCode}")
    @ApiOperation(value = "根据邀请码查询", notes = "根据邀请码查询平台消费者信息", consumes = MediaType.ALL_VALUE)
    public Response findByName(@PathVariable("inviteCode") String inviteCode) {
        Response rs;
        try {
            PlatConsumer entity = new PlatConsumer();
            entity.setInviteCode(inviteCode);
            rs = Response.data(platMemberService.List(entity));
        } catch (Exception e) {
            logger.error("根据邀请码查询平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询平台消费者信息（get请求，以具体值接收参数）
     * @param pageIndex     当前页码
     * @param pageSize      每页显示的记录数
     * @param inviteCode    邀请码
     * @param regShare      注册方式
     * @param channel       渠道
     * @return Response
     */
    @GetMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询平台消费者信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "当前页码", required = true, dataType = "Long", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "Long", example = "10", paramType = "query"),
            @ApiImplicitParam(name = "inviteCode", value = "邀请码", dataType = "String", example = "123", paramType = "query"),
            @ApiImplicitParam(name = "regShare", value = "注册方式", dataType = "Integer", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "channel", value = "渠道", dataType = "Integer", example = "1", paramType = "query")
    })
    public Response list(Long pageIndex, Long pageSize, String inviteCode, Integer regShare, Integer channel) {
        Response rs;
        try {
            PlatConsumer entity = new PlatConsumer();
            entity.setPageIndex(pageIndex);
            entity.setPageSize(pageSize);
            entity.setInviteCode(inviteCode);
            entity.setRegShare(regShare);
            entity.setChannel(channel);
            rs = Response.data(platMemberService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询平台消费者信息（post请求，以对象接收参数）
     * @param param 查询参数实体
     * @return Response
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询平台消费者信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response list(@RequestBody PlatConsumerPageParam param) {
        Response rs;
        try {
            PlatConsumer entity = new PlatConsumer();
            BeanUtils.copyProperties(param, entity);
            rs = Response.data(platMemberService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据参数查询平台消费者信息
     * @param param 参数
     * @return Response
     */
    @PostMapping("/getConsumers")
    @ApiOperation(value = "根据参数查询", notes = "根据参数查询平台消费者信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<PlatConsumer> getConsumers(@RequestBody PlatConsumer param) {
        Response rs;
        try {
            rs = Response.data(platMemberService.getConsumers(param));
        } catch (Exception e) {
            logger.error("根据参数查询平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed();
        }
        return rs;
    }

    /**
     * 新增平台消费者信息
     * @param entity 保存参数实体
     * @return Response
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增平台消费者信息", notes = "新增平台消费者信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> save(@RequestBody @Valid PlatConsumer entity) {
        return Response.data(platMemberService.insert(entity));
    }

    /**
     * 修改平台消费者信息
     * @param param 修改参数实体
     * @return Response
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改平台消费者信息", notes = "修改平台消费者信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> updateById(@RequestBody @Valid PlatConsumerUpdateParam param, BindingResult result) {
        PlatConsumer entity = new PlatConsumer();
        try {
            BeanUtils.copyProperties(param, entity);
        }catch (Exception e){
            throw new ServiceException("Bean转换异常");
        }
        return Response.data(platMemberService.update(entity));
    }

    /**
     * 根据ID删除平台消费者信息
     * @param id 用户ID
     * @return Response
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除平台消费者信息", consumes = MediaType.ALL_VALUE)
    public Response deleteById(@PathVariable("id") Long id) {
        Response rs;
        try {
            rs = Response.data(platMemberService.delete(id));
        } catch (ServiceException e) {
            logger.error("删除平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("删除平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID获取平台消费者信息
     * @param id 用户ID
     * @return Response
     */
    @DeleteMapping("/accountInfo/{id}")
    @ApiOperation(value = "根据ID获取平台消费者信息", notes = "根据ID获取平台消费者信息", consumes = MediaType.ALL_VALUE)
    public Response getAccountInfoById(@PathVariable("id") Long id) {
        Map<String,Object> map = new HashMap<>();
        Response rs;
        try {
            // 获取平台消费者信息
            PlatConsumer consumer = platMemberService.getById(id);
            // 获取平台消费者账户信息
            MemberAccount memberAccount = memberAccountService.getMemberAccountByConsumerId(consumer.getId());
            // 获取平台消费者积分信息
            MemberIntegration memberIntegration = memberIntegrationService.getMemberIntegrationsByConsumerId(consumer.getId());
            //  组装信息
            map.put("memberId",consumer.getMemberId());                         // 租户会员id
            map.put("companyId",consumer.getCompanyId());                       // 租户id
            map.put("platformId",consumer.getPlatformId());                     // 平台id
            map.put("accountBalance",memberAccount.getAvailableBalance());      // 账户余额
            map.put("freezAmount",memberAccount.getFreezingAmount());           // 冻结金额
            map.put("points",memberIntegration.getAmount());                    // 积分
            //TODO--积分表少一个冻结积分字段，暂时先返回0
            map.put("freezPoints", 0);                                          // 冻结积分
            rs = Response.data(map);
        } catch (ServiceException e) {
            logger.error("根据ID获取平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("根据ID获取平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    @PostMapping("/getStoreConsumerPage")
    @ApiOperation(value = "分页查询店铺消费者列表",notes = "分页查询店铺消费者列表",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Page<MemberDto>> getStoreConsumerPage(@RequestBody PlatStoreConsumerPageParam param){
        Response rs;
        try {
            // 根据店铺ID查询
            Page<MemberDto> page= platMemberService.getStoreConsumerPage(param);
            rs = Response.data(page);
        } catch (ServiceException e) {
            logger.error("根据ID获取平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("根据ID获取平台消费者信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }
}
